package com.yunkaweilai.android.fragment.operation;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.google.gson.Gson;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.base.BaseFragment;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.constants.CommonConstants;
import com.yunkaweilai.android.interfaces.GoodsZeroInterfaces;
import com.yunkaweilai.android.interfaces.PopupShopSpecification;
import com.yunkaweilai.android.interfaces.UpdateGoodsNumInterfaces;
import com.yunkaweilai.android.model.Event;
import com.yunkaweilai.android.model.PayTypeModel;
import com.yunkaweilai.android.model.shop.ShopModel;
import com.yunkaweilai.android.model.shop.ShopSkuInfoModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.utils.zxing.Kutils;
import com.yunkaweilai.android.view.dialog.GoodsStockZeroDialog;
import com.yunkaweilai.android.view.dialog.UpdateGoodsNumDialog;
import com.yunkaweilai.android.view.popup.ShopSpecificationPopup;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;

/**
 * 商品列表
 * Created by Administrator on 2017/6/13.
 */

public class PtShopListFragment extends BaseFragment implements BGARefreshLayout.BGARefreshLayoutDelegate, PopupShopSpecification, GoodsZeroInterfaces, UpdateGoodsNumInterfaces {
    @BindView(R.id.id_listView)
    ListView idListView;
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView idMultipleStatusView;
    @BindView(R.id.content_view)
    BGARefreshLayout contentView;
    @BindView(R.id.id_view)
    View idView;

    Unbinder unbinder;
    private String goods_category_id = "";
    private PayTypeModel payTypeModel = BaseApplication.payModel;
    private ArrayList<ShopModel.DataBean.ListBean> shoplist = new ArrayList<>();
    private CommonAdapter<ShopModel.DataBean.ListBean> adapter;
    private int mpage = 1;
    private boolean mHasMore = true;
    public static Map<String, ShopSkuInfoModel> selectedMaps = new HashMap<>();
    private Gson gson = new Gson();

    public static PtShopListFragment getInstentce(String goods_category_id) {
        PtShopListFragment fragment = new PtShopListFragment();
        fragment.goods_category_id = goods_category_id;
        return fragment;
    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_list;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        initRefreshLayout(contentView, this, true);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        selectedMaps = BaseApplication.getSelectedMaps();
        initAdapter();
        idMultipleStatusView.showLoading();
        idMultipleStatusView.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initHttp(true);
            }
        });
        initHttp(true);

    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onShopEvent(Event.TypeEvent event) {
        if (event != null) {
            if (event.type == CommonConstants.SHOP_CART_INFO_REFRESH) {
                if (event.flag) {
                    selectedMaps = BaseApplication.getSelectedMaps();
                    adapter.notifyDataSetChanged();
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }


    private boolean initHttp(final boolean refresh) {
        mpage = refresh ? 1 : mpage;
        if ((!mHasMore) && (!refresh)) {
            contentView.endLoadingMore();
            showToast("没有更多数据了");
            return false;
        }
        HttpRequest.postUrl(Api.SHOP_INFO_LIST)
                .addParams("ShowPage", "1")
                .addParams("PageSize", "10")
                .addParams("CurrPage", mpage + "")
                .addParams("is_show_status", "1")
                .addParams("goods_category_id", goods_category_id).log(TAG)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        endRefreshOrLoad(refresh);
                        Gson gson = new Gson();
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            mpage++;
                            ShopModel shopModel = gson.fromJson(json, ShopModel.class);
                            if (refresh) {
                                shoplist.clear();
                            }

                            if (shopModel.getData().getList() != null && shopModel.getData().getList().size() != 0) {
                                shoplist.addAll(shopModel.getData().getList());
                                adapter.notifyDataSetChanged();
                                EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_CART_INFO_REFRESH, true));
                                mHasMore = shopModel.getData().getPage().isNext();//如果接收到完整10个数据，说明还有下一页
                                if (idMultipleStatusView != null) {
                                    idMultipleStatusView.showContent();
                                }
                            } else {
                                mHasMore = false;
                                if (refresh) {
                                    if (idMultipleStatusView != null) {
                                        idMultipleStatusView.showEmpty();
                                    }
                                }
                            }
                        } else {
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showError();
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        if (idMultipleStatusView != null) {
                            idMultipleStatusView.showError();
                        }
                    }
                });
        return true;
    }

    /**
     * 结束刷新组件
     *
     * @param refresh
     */
    private void endRefreshOrLoad(boolean refresh) {
        if (refresh) {
            if (contentView != null) {
                contentView.endRefreshing();
            }
        } else {
            if (contentView != null) {
                contentView.endLoadingMore();
            }
        }
    }

    private void initAdapter() {
        adapter = new CommonAdapter<ShopModel.DataBean.ListBean>(getActivity(), R.layout.item_list_shop_consumption, shoplist) {
            @Override
            protected void convert(ViewHolder viewHolder, final ShopModel.DataBean.ListBean item, int position) {
                viewHolder.setVisible(R.id.id_tv_duo, false);
                ImageView mIdImg = viewHolder.getView(R.id.id_img);
                Utils.shopInfoImg(mAc, item.getGoods_image(), mIdImg);

                viewHolder.setText(R.id.id_tv_name, item.getGoods_name() + "");
                viewHolder.setText(R.id.id_tv_price, item.getShow_shop_price() + "");
                viewHolder.setText(R.id.id_tv_unit, "/" + item.getUnit());
                viewHolder.setText(R.id.id_tv_info, "库存：" + item.getMay_use_stock());
                if (item.getSkuList().size() > 1) {
                    viewHolder.setVisible(R.id.id_tv_duo, true);
                }
//                viewHolder.setText(R.id.id_tv_info, "编号：" + item.getGoods_sku() + " 库存：" + item.getMay_use_stock());
                Double size = 0D;
                for (String key : selectedMaps.keySet()) {
                    ShopSkuInfoModel shopSkuInfoModel = selectedMaps.get(key);
                    if (item.getSkuList().size() > 1) {
                        for (int i = 0; i < item.getSkuList().size(); i++) {
                            ShopSkuInfoModel itemSkuModel = item.getSkuList().get(i);
                            if (itemSkuModel.getSku().equals(shopSkuInfoModel.getSku())) {
                                size = size + shopSkuInfoModel.getBuy_num();
                            }
                        }
                    } else {
                        ShopSkuInfoModel itemSkuModel = item.getSkuList().get(0);
                        if (shopSkuInfoModel.getSku().equals(itemSkuModel.getSku())) {
                            size = size + shopSkuInfoModel.getBuy_num();
                        }
                    }
                }
                ImageView idImgAdd = viewHolder.getView(R.id.id_img_add);
                ImageView idImgDel = viewHolder.getView(R.id.id_img_del);
                TextView idTvAddNum = viewHolder.getView(R.id.id_tv_add_num);
                if (size > 0) {
                    idImgDel.setVisibility(View.VISIBLE);

                    idTvAddNum.setText(Utils.MoneyQuZheng(Utils.ManageCount(size + "")) + "");
                    idTvAddNum.setVisibility(View.VISIBLE);
                } else {
                    idImgDel.setVisibility(View.GONE);
                    idTvAddNum.setText("0");
                    idTvAddNum.setVisibility(View.GONE);
                }
                idTvAddNum.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (item.getSkuList().size() == 1) {
                            ShopSkuInfoModel shopSkuInfoModel = selectedMaps.get(item.getSkuList().get(0).getSku());
                            UpdateGoodsNumDialog dialog = new UpdateGoodsNumDialog(mAc, shopSkuInfoModel, PtShopListFragment.this, "修改数量");
                            dialog.setCanceledOnTouchOutside(false);
                            dialog.show();
                        }
                    }
                });
                //增加
                idImgAdd.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //是否多规格
                        if (item.getSkuList().size() > 1) {
                            ShopSpecificationPopup shopPopup = new ShopSpecificationPopup(mAc, item);
                            shopPopup.setInterface(PtShopListFragment.this);
                            shopPopup.showPopupWindow();
                        } else {
                            ShopSkuInfoModel shopSkuInfoModel = selectedMaps.get(item.getSkuList().get(0).getSku());
                            if (shopSkuInfoModel == null) {
                                if (item.isOpen_stock() && 1 > item.getSkuList().get(0).getMay_use_stock() && "0".equals(payTypeModel.getData().getInfo().getIs_open_stock())) {
                                    GoodsStockZeroDialog dialog = new GoodsStockZeroDialog(mAc, PtShopListFragment.this, "1", item, shopSkuInfoModel);
                                    dialog.setCanceledOnTouchOutside(false);
                                    dialog.show();
//                                    showToast("库存不足");
                                } else {
                                    int[] startLocation = new int[2];// 一个整型数组，用来存储按钮的在屏幕的X、Y坐标
                                    v.getLocationInWindow(startLocation);// 这是获取购买按钮的在屏幕的X、Y坐标（这也是动画开始的坐标）
                                    ImageView ball = new ImageView(mAc);// buyImg是动画的图片，我的是一个小球
                                    ball.setImageResource(R.mipmap.ic_shop_buy_red_point);// 设置buyImg的图片
                                    setAnim(ball, startLocation);//动画开启，在结束时，修改购物车
                                    item.getSkuList().get(0).setBuy_num(1);
                                    item.getSkuList().get(0).setGoods_type(item.getGoods_type());
                                    item.getSkuList().get(0).setGoods_category_parent_id(item.getGoods_category_parent_id());
                                    item.getSkuList().get(0).setEmplyeeStr("");
                                    item.getSkuList().get(0).setEmplyeeName("");
                                    selectedMaps.put(item.getSkuList().get(0).getSku(), item.getSkuList().get(0));
                                }
                            } else {
                                if (item.isOpen_stock() && item.getSkuList().get(0).getMay_use_stock() <= shopSkuInfoModel.getBuy_num() && "0".equals(payTypeModel.getData().getInfo().getIs_open_stock())) {
                                    GoodsStockZeroDialog dialog = new GoodsStockZeroDialog(mAc, PtShopListFragment.this, "2", item, shopSkuInfoModel);
                                    dialog.setCanceledOnTouchOutside(false);
                                    dialog.show();
//                                    showToast("库存不足");
                                } else {
                                    int[] startLocation = new int[2];// 一个整型数组，用来存储按钮的在屏幕的X、Y坐标
                                    v.getLocationInWindow(startLocation);// 这是获取购买按钮的在屏幕的X、Y坐标（这也是动画开始的坐标）
                                    ImageView ball = new ImageView(mAc);// buyImg是动画的图片，我的是一个小球
                                    ball.setImageResource(R.mipmap.ic_shop_buy_red_point);// 设置buyImg的图片
                                    setAnim(ball, startLocation);//动画开启，在结束时，修改购物车
                                    shopSkuInfoModel.setBuy_num(shopSkuInfoModel.getBuy_num() + 1);
                                }
                            }
                            adapter.notifyDataSetChanged();

                        }
                    }
                });
                //减少
                idImgDel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //是否多规格
                        if (item.getSkuList().size() > 1) {
                            showToast("多规格商品只能去购物车修改");
                        } else {
                            ShopSkuInfoModel shopSkuInfoModel = selectedMaps.get(item.getSkuList().get(0).getSku());

                            if (shopSkuInfoModel == null) {
//                                double nums = item.getSkuList().get(0).getBuy_num() - 1;
                                double nums = Kutils.sub(item.getSkuList().get(0).getBuy_num(), 1);


                                item.getSkuList().get(0).setBuy_num(nums <= 0 ? 0 : nums);
                                if (nums > 0) {
                                    item.getSkuList().get(0).setGoods_type("Putong");
                                    item.getSkuList().get(0).setGoods_category_parent_id(item.getGoods_category_parent_id());
                                    selectedMaps.put(item.getSkuList().get(0).getSku(), item.getSkuList().get(0));
                                }
                            } else {
                                double buy_num = shopSkuInfoModel.getBuy_num();
                                if (buy_num - 1 > 0) {
                                    shopSkuInfoModel.setBuy_num(Kutils.sub(buy_num, 1));
                                } else {
                                    item.getSkuList().get(0).setBuy_num(0);
                                    selectedMaps.remove(shopSkuInfoModel.getSku());
                                    BaseApplication.selectedMaps = selectedMaps;
                                }
                            }
                            adapter.notifyDataSetChanged();
                            EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_CART_INFO_REFRESH, true));
                        }
                    }
                });

            }
        };
        idListView.setAdapter(adapter);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        initHttp(true);
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        return initHttp(false);
    }

    //多规格商品选择
    @Override
    public void addSku(ShopSkuInfoModel skuInfoModel, String goods_category_parent_id, boolean isflag) {
        if (isflag) {
            ShopSkuInfoModel shopSkuInfoModel = selectedMaps.get(skuInfoModel.getSku());
            if (shopSkuInfoModel == null) {
                skuInfoModel.setBuy_num(skuInfoModel.getBuy_num() + 1);
                skuInfoModel.setGoods_type("Putong");
                skuInfoModel.setGoods_category_parent_id(goods_category_parent_id);
                selectedMaps.put(skuInfoModel.getSku(), skuInfoModel);
            } else {
                shopSkuInfoModel.setBuy_num(shopSkuInfoModel.getBuy_num() + 1);
            }
            adapter.notifyDataSetChanged();
            EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_CART_INFO_REFRESH, true));
        } else {
            ShopSkuInfoModel shopSkuInfoModel = selectedMaps.get(skuInfoModel.getSku());
            if (shopSkuInfoModel == null) {
                skuInfoModel.setBuy_num(skuInfoModel.getBuy_num());
                skuInfoModel.setGoods_type("Putong");
                skuInfoModel.setGoods_category_parent_id(goods_category_parent_id);
                selectedMaps.put(skuInfoModel.getSku(), skuInfoModel);
            } else {
                shopSkuInfoModel.setBuy_num(shopSkuInfoModel.getBuy_num());
            }
            GoodsStockZeroDialog dialog = new GoodsStockZeroDialog(mAc, PtShopListFragment.this, "2", null, selectedMaps.get(skuInfoModel.getSku()));
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
        }

    }

    //商品增加的动画
    private ViewGroup anim_mask_layout;//动画层

    public void setAnim(final View v, int[] startLocation) {
        anim_mask_layout = null;
        anim_mask_layout = createAnimLayout();
        anim_mask_layout.addView(v);//把动画小球添加到动画层
        final View view = addViewToAnimLayout(anim_mask_layout, v,
                startLocation);
        int[] endLocation = new int[2];// 存储动画结束位置的X、Y坐标
        //TODO 这里需要进行判断购物车是否存在
        idView.getLocationInWindow(endLocation);// shopCart是那个购物车
        // 计算位移
        int endX = 0 - startLocation[0] + 60;// 动画位移的X坐标
        int endY = endLocation[1] - startLocation[1];// 动画位移的y坐标
        TranslateAnimation translateAnimationX = new TranslateAnimation(0,
                endX, 0, 0);
        translateAnimationX.setInterpolator(new LinearInterpolator()); //让动画已均匀的速度改变
        translateAnimationX.setRepeatCount(0);// 动画重复执行的次数
        translateAnimationX.setFillAfter(true); //执行完毕，利用视图setLayoutParams来重新定位

        TranslateAnimation translateAnimationY = new TranslateAnimation(0, 0,
                0, endY);
        translateAnimationY.setInterpolator(new AccelerateInterpolator());
        translateAnimationY.setRepeatCount(0);// 动画重复执行的次数
        translateAnimationX.setFillAfter(true);

        AnimationSet set = new AnimationSet(false);
        set.setFillAfter(false);
        set.addAnimation(translateAnimationY);
        set.addAnimation(translateAnimationX);
        set.setDuration(800);// 动画的执行时间
        view.startAnimation(set);
        // 动画监听事件
        set.setAnimationListener(new Animation.AnimationListener() {
            // 动画的开始
            @Override
            public void onAnimationStart(Animation animation) {
                v.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
                // TODO Auto-generated method stub
            }

            // 动画的结束
            @Override
            public void onAnimationEnd(Animation animation) {
                v.setVisibility(View.GONE);
                EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_CART_INFO_REFRESH, true));
            }
        });

    }


    /**
     * 创建动画层
     *
     * @return
     */
    private ViewGroup createAnimLayout() {
        ViewGroup rootView = (ViewGroup) mAc.getWindow().getDecorView();
        LinearLayout animLayout = new LinearLayout(mAc);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        animLayout.setLayoutParams(lp);
        animLayout.setId(Integer.MAX_VALUE - 1);
        animLayout.setBackgroundResource(android.R.color.transparent);
        rootView.addView(animLayout);
        return animLayout;
    }

    private View addViewToAnimLayout(final ViewGroup parent, final View view,
                                     int[] location) {
        int x = location[0];
        int y = location[1];
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.leftMargin = x;
        lp.topMargin = y;
        view.setLayoutParams(lp);
        return view;
    }


    //库存为0添加
    @Override
    public void addGoods(String type, ShopModel.DataBean.ListBean item, ShopSkuInfoModel shopSkuInfoModel) {
        if ("1".equals(type)) {
            item.getSkuList().get(0).setBuy_num(1);
            item.getSkuList().get(0).setGoods_type(item.getGoods_type());
            item.getSkuList().get(0).setGoods_category_parent_id(item.getGoods_category_parent_id());
            item.getSkuList().get(0).setEmplyeeStr("");
            item.getSkuList().get(0).setEmplyeeName("");
            selectedMaps.put(item.getSkuList().get(0).getSku(), item.getSkuList().get(0));
            EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_CART_INFO_REFRESH, true));
            adapter.notifyDataSetChanged();
        } else if ("2".equals(type)) {
            shopSkuInfoModel.setBuy_num(shopSkuInfoModel.getBuy_num() + 1);
            EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_CART_INFO_REFRESH, true));
            adapter.notifyDataSetChanged();
        }
        item.setOpen_stock(false);
    }

    @Override
    public void refreshGoods() {
        EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_CART_INFO_REFRESH, true));
        adapter.notifyDataSetChanged();
    }
}
